/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.biz.service.impl;

import me.zhengjie.modules.biz.domain.Announcement;
import me.zhengjie.modules.biz.domain.Lab;
import me.zhengjie.modules.biz.domain.Message;
import me.zhengjie.modules.biz.service.dto.CabinetDto;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.repository.MessageRepository;
import me.zhengjie.modules.biz.service.MessageService;
import me.zhengjie.modules.biz.service.dto.MessageDto;
import me.zhengjie.modules.biz.service.dto.MessageQueryCriteria;
import me.zhengjie.modules.biz.service.mapstruct.MessageMapper;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author Admin
* @date 2023-02-18
**/
@Service
@RequiredArgsConstructor
public class MessageServiceImpl implements MessageService {

    private final MessageRepository messageRepository;
    private final UserRepository userRepository;
    private final MessageMapper messageMapper;

    @Override
    public Map<String,Object> queryAll(MessageQueryCriteria criteria, Pageable pageable){
        Page<Message> page = messageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Page<MessageDto> dto = page.map(messageMapper::toDto);
        List<MessageDto> resultDto = dto.getContent();
        for (MessageDto messageDto:resultDto) {
            User user = userRepository.findById(Long.valueOf(messageDto.getUserId())).orElseGet(User::new);
            messageDto.setUserName(user.getUsername());
        }
        return PageUtil.toPage(dto);
    }

    @Override
    public List<MessageDto> queryAll(MessageQueryCriteria criteria){
        List<Message> messageList = messageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
        List<MessageDto> messageDtoList = messageMapper.toDto(messageList);
        for (MessageDto messageDto : messageDtoList) {
            User user = userRepository.findById(Long.valueOf(messageDto.getUserId())).orElseGet(User::new);
            messageDto.setUserName(user.getUsername());
        }
        return messageDtoList;
    }

    @Override
    @Transactional
    public MessageDto findById(Integer id) {
        Message message = messageRepository.findById(id).orElseGet(Message::new);
        ValidationUtil.isNull(message.getId(),"Message","id",id);
        return messageMapper.toDto(message);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MessageDto create(Message resources) {
        return messageMapper.toDto(messageRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Message resources) {
        Message message = messageRepository.findById(resources.getId()).orElseGet(Message::new);
        ValidationUtil.isNull( message.getId(),"Message","id",resources.getId());
        message.copy(resources);
        messageRepository.save(message);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            messageRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<MessageDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (MessageDto message : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            String type = "";
            switch (message.getType()) {
                case 1:
                    type = "报警日志";
                    break;
                case 2:
                    type = "其他日志";
                    break;
            }
            map.put("类型", type);
            map.put("内容", message.getName());
            map.put("接收人", message.getUserName());
            map.put("创建时间",  message.getCreatedAt());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Map<String,Object> queryReadMessage(MessageQueryCriteria criteria, Pageable pageable) {
        Specification<Message> specification =  (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            predicates.add(criteriaBuilder.equal(root.get("isRead").as(Integer.class), 1));
            predicates.add(criteriaBuilder.equal(root.get("userId"),  SecurityUtils.getCurrentUserId()));
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<Message> page = messageRepository.findAll(specification, pageable);
        return PageUtil.toPage(page.map(messageMapper::toDto));
    }

    @Override
    public Map<String,Object> queryUnReadMessage(MessageQueryCriteria criteria, Pageable pageable) {
        Specification<Message> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            predicates.add(criteriaBuilder.equal(root.get("isRead").as(Integer.class), 0));
            predicates.add(criteriaBuilder.equal(root.get("userId"),  SecurityUtils.getCurrentUserId()));
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<Message> page = messageRepository.findAll(specification, pageable);
        return PageUtil.toPage(page.map(messageMapper::toDto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void read(Integer id) {
        messageRepository.updateById(id);
    }
}
